package com.lk;

public class TestProducerConsumer {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        Producer producer = new Producer(clerk);
        Consumer consumer = new Consumer(clerk);
        new Thread(producer).start();
        new Thread(consumer).start();

        new Thread(producer).start();
        new Thread(consumer).start();
    }
}

class Clerk{
    int num=0;
    public synchronized void get(){
        while(num>=10){
            System.out.println("库存已满");
            try {
                Thread.sleep(400);
                this.wait();
            } catch (InterruptedException e) {
            }
        }
        System.out.println(Thread.currentThread().getName()+" : " + ++num);
        this.notifyAll();
    }

    public synchronized void sale(){
        while(num<=0){
            System.out.println("没有库存");
            try {
                Thread.sleep(400);
                this.wait();
            } catch (InterruptedException e) {
            }
        }
        System.out.println(Thread.currentThread().getName()+ " : " + --num);
        this.notifyAll();
    }
}

class Producer implements Runnable{

    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++) {
            clerk.get();
        }
    }
}

class Consumer implements Runnable{
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++){
            clerk.sale();
        }
    }
}
